package com.lmh.friend.service.user.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lmh.common.core.constants.Constants;
import com.lmh.common.core.domain.R;
import com.lmh.common.core.domain.TableDataInfo;
import com.lmh.common.core.domain.dto.PageQueryDTO;
import com.lmh.common.core.enums.ResultCode;
import com.lmh.common.core.utils.ThreadLocalUtil;
import com.lmh.common.security.exception.ServiceException;
import com.lmh.friend.domain.message.Message;
import com.lmh.friend.domain.message.MessageText;
import com.lmh.friend.domain.message.vo.MessageTextVO;
import com.lmh.friend.manager.MessageCacheManager;
import com.lmh.friend.mapper.message.MessageMapper;
import com.lmh.friend.mapper.message.MessageTextMapper;
import com.lmh.friend.service.user.IUserMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserMessageServiceImpl implements IUserMessageService {
    @Autowired
    private MessageCacheManager messageCacheManager;

    @Autowired
    private MessageTextMapper messageTextMapper;

    @Autowired
    private MessageMapper messageMapper;

    @Override
    public TableDataInfo list(PageQueryDTO dto) {
        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        Long total = messageCacheManager.getListSize(userId);
        List<MessageTextVO> messageTextVOList = new ArrayList<>();
        if (total == null || total <= 0) {
            // 说明缓存中不存在用户消息列表，那么就从数据库中拿
            PageHelper.startPage(dto.getPageNum(),dto.getPageSize());
            messageTextVOList = messageTextMapper.selectUserMsgList(userId);
            messageCacheManager.refreshCache(userId);
            total = new PageInfo<>(messageTextVOList).getTotal();
        }else {
            messageTextVOList = messageCacheManager.getMsgTextVOList(dto,userId);
        }
        if (CollectionUtil.isEmpty(messageTextVOList)) {
            return TableDataInfo.empty();
        }
        return TableDataInfo.success(messageTextVOList, total);
    }

    @Transactional
    @Override
    public R<Void> delete(Long textId) {
        // 首先对前端传来的参数进行校验，也就是检查要删除的msg是否存在
        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        MessageText messageText = messageTextMapper.selectById(textId);
        Message message = messageMapper.selectOne(new LambdaQueryWrapper<Message>()
                        .eq(Message::getRecId,userId)
                        .eq(Message::getTextId,textId));
        if (messageText == null || message == null) {
            throw new ServiceException(ResultCode.FAILED_MESSAGE_NOT_EXIST);
        }
        // 先将redis缓存中的数据删除
        boolean res = messageCacheManager.deleteCache(textId,userId);
        if (!res) {
            throw new ServiceException(ResultCode.ERROR);
        }
        // 然后将消息从数据库中删除
        int ret = messageTextMapper.deleteById(textId);
        if (ret <= 0) {
            throw new ServiceException(ResultCode.ERROR);
        }
        ret = messageMapper.delete(new LambdaQueryWrapper<Message>()
                .eq(Message::getRecId,userId)
                .eq(Message::getTextId,textId));
        if (ret <= 0) {
            throw new ServiceException(ResultCode.ERROR);
        }
        return R.ok();
    }
}
